import { fallbackRequestGet } from '@/utils/Request'
import { ResultCode } from '@/constants/constants'

/**
 * 请求前缀，后面后台添加网关后需要前缀选择微服务
 */
const URL_PREFIX = 'middle-user/'

/**
 * Session注册，防止session丢失导致的第一次无Cookie时的Session不一致问题
 * @param successCallback 成功回调
 * @param fullCallback 全回调
 * @return {*} 结果
 */
export const sessionRegister = (successCallback = null, fullCallback = null) => {
  return fallbackRequestGet(URL_PREFIX + 'init/sessionRegister', {}, {}, false,
    successCallback, null, fullCallback)
}

// 间隔时间，单位毫秒，这里是10分钟
const freshTime = 10 * 60 * 1000
// 每次间隔执行次数
const freshSize = 3

// 定时器ID
let intervalID

const sessionRegisterTemp = (size) => {
  sessionRegister(data => {
    size++
    if (data && data.code === ResultCode.OK) {
      console.info('sessionRegister 成功 ' + size)
    }
    if (size < freshSize) {
      sessionRegisterTemp(size)
    }
  })
}

/**
 * 开启session心跳
 */
export const startSessionRegister = () => {
  if (intervalID) {
    clearInterval(intervalID)
    intervalID = undefined
  }
  const fun = () => {
    let size = 0
    sessionRegisterTemp(size)
  }
  intervalID = setInterval(fun, freshTime)
  fun()
}

/**
 * 停止session心跳
 */
export const stopSessionRegister = () => {
  if (intervalID) {
    clearInterval(intervalID)
    intervalID = undefined
  }
}
